package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.dto.contest.ContestAddRequest;
import com.yupi.yuoj.model.dto.contest.ContestEditRequest;
import com.yupi.yuoj.model.dto.contest.ContestQueryRequest;
import com.yupi.yuoj.model.dto.contest.ContestRegistrationRequest;
import com.yupi.yuoj.model.entity.Contest;
import com.yupi.yuoj.model.entity.ContestRegistration;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.ContestRankVO;
import com.yupi.yuoj.model.vo.ContestVO;
import com.yupi.yuoj.service.ContestRegistrationService;
import com.yupi.yuoj.service.ContestService;
import com.yupi.yuoj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 竞赛接口
 */
@RestController
@RequestMapping("/contest")
@Slf4j
public class ContestController {

    @Resource
    private ContestService contestService;

    @Resource
    private ContestRegistrationService contestRegistrationService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建竞赛
     *
     * @param contestAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addContest(@RequestBody ContestAddRequest contestAddRequest, HttpServletRequest request) {
        if (contestAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long contestId = contestService.addContest(contestAddRequest, request);
        return ResultUtils.success(contestId);
    }

    /**
     * 删除竞赛
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteContest(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Contest oldContest = contestService.getById(id);
        ThrowUtils.throwIf(oldContest == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldContest.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = contestService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新竞赛
     *
     * @param contestEditRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateContest(@RequestBody ContestEditRequest contestEditRequest,
            HttpServletRequest request) {
        if (contestEditRequest == null || contestEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = contestService.updateContest(contestEditRequest, request);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取竞赛
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<ContestVO> getContestById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Contest contest = contestService.getById(id);
        if (contest == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 更新竞赛状态
        contestService.updateContestStatus(contest);
        ContestVO contestVO = contestService.getContestVO(contest, request);
        return ResultUtils.success(contestVO);
    }

    /**
     * 分页获取竞赛列表
     *
     * @param contestQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<ContestVO>> listContestByPage(@RequestBody ContestQueryRequest contestQueryRequest,
            HttpServletRequest request) {
        long current = contestQueryRequest.getCurrent();
        long size = contestQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Contest> contestPage = contestService.page(new Page<>(current, size),
                contestService.getQueryWrapper(contestQueryRequest));
        // 更新竞赛状态
        for (Contest contest : contestPage.getRecords()) {
            contestService.updateContestStatus(contest);
        }
        return ResultUtils.success(contestService.getContestVOPage(contestPage, request));
    }

    // endregion

    /**
     * 注册竞赛
     *
     * @param contestRegistrationRequest
     * @param request
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<ContestRegistration> registerContest(@RequestBody ContestRegistrationRequest contestRegistrationRequest,
            HttpServletRequest request) {
        if (contestRegistrationRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ContestRegistration registration = contestService.registerContest(contestRegistrationRequest, request);
        return ResultUtils.success(registration);
    }

    /**
     * 用户开始竞赛
     *
     * @param contestId
     * @param request
     * @return
     */
    @PostMapping("/start")
    public BaseResponse<ContestRegistration> startContest(Long contestId, HttpServletRequest request) {
        if (contestId == null || contestId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        ContestRegistration registration = contestRegistrationService.startContest(contestId, loginUser.getId());
        return ResultUtils.success(registration);
    }

    /**
     * 用户结束竞赛
     *
     * @param contestId
     * @param request
     * @return
     */
    @PostMapping("/finish")
    public BaseResponse<ContestRegistration> finishContest(Long contestId, HttpServletRequest request) {
        if (contestId == null || contestId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        ContestRegistration registration = contestRegistrationService.finishContest(contestId, loginUser.getId());
        return ResultUtils.success(registration);
    }

    /**
     * 获取竞赛排名
     *
     * @param contestId
     * @return
     */
    @GetMapping("/rank")
    public BaseResponse<List<ContestRankVO>> getContestRank(Long contestId) {
        if (contestId == null || contestId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 更新所有用户排名
        contestRegistrationService.updateRankings(contestId);
        List<ContestRankVO> rankList = contestRegistrationService.getContestRanking(contestId);
        return ResultUtils.success(rankList);
    }

    /**
     * 获取我已注册的竞赛
     *
     * @param request
     * @return
     */
    @GetMapping("/my/registered")
    public BaseResponse<List<ContestVO>> getMyRegisteredContests(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        List<ContestVO> contestVOList = contestService.getRegisteredContests(loginUser.getId(), request);
        return ResultUtils.success(contestVOList);
    }

    /**
     * 获取我创建的竞赛
     *
     * @param request
     * @return
     */
    @GetMapping("/my/created")
    public BaseResponse<List<ContestVO>> getMyCreatedContests(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        ContestQueryRequest contestQueryRequest = new ContestQueryRequest();
        contestQueryRequest.setUserId(loginUser.getId());
        List<Contest> contestList = contestService.list(contestService.getQueryWrapper(contestQueryRequest));
        List<ContestVO> contestVOList = contestList.stream()
                .map(contest -> contestService.getContestVO(contest, request))
                .collect(Collectors.toList());
        return ResultUtils.success(contestVOList);
    }
} 